import { Component, OnInit, TemplateRef, OnDestroy, AfterViewInit, ViewChild } from '@angular/core';
import { NzSubMenuComponent } from 'ng-zorro-antd';
import { ToolsService, BullySubjectService, Bully, MessagesService } from 'app/shared/service';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs';
import { SystemService } from 'app/service/system.service';
import { SYSTEM_EVENT, MESSAGE_CHANNEL } from 'app/app.constants';
import { DialogService } from 'app/shared/dialog';
import { ConfigService } from 'app/config/config.service';
import { LoginService } from 'app/auth/login.service';
import { AuthService } from 'app/auth/auth.service';
import { filter } from 'rxjs/operators';

export interface MenuItem {
    title: string;
    route?: string;
    id?: string; // 有children元素的menu的id , 无childrensubmenu或submenu无id
    icon?: string;
    exponded?: boolean; // 控制 有children的节点的展开状态
    active?: boolean; //  控制 有children的节点的激活状态
    children?: Array<MenuItem>;
    // 后台返回的数据结构
    accessId?: number;
    rightName?: string;
    parentId?: number;
    url?: string;
    description?: string;
    show?: boolean;
    accesstype?: 'button' | 'menu';
}

@Component({
    selector: 'itmp-layouts',
    templateUrl: './layouts.component.html',
    styleUrls: ['./layouts.css']
})
export class LayoutsComponent implements OnInit, OnDestroy, AfterViewInit {
    @ViewChild('submenuRef') submenuRef: NzSubMenuComponent = null;
    // private _submenuRefMap: Map<string, NzSubMenuComponent> = new Map<string, NzSubMenuComponent>();
    // private _currentId = null; // 用于收缩后记住点击的submenu所在的menu的id
    isCollapsed = false;
    triggerTemplate: TemplateRef<void> | null = null;
    subscriptions: Subscription[] = [];
    menuList: Array<MenuItem> = [];
    hostName = this.config.itmpHostName;
    showPage = false;

    linkClickId: any = '';
    constructor(
        private tools: ToolsService,
        private router: Router,
        public systemService: SystemService,
        private config: ConfigService,
        private bully: BullySubjectService,
        private dialog: DialogService,
        private ls: LoginService,
        private auth: AuthService,
        private msg: MessagesService
    ) {
        // 判断本地token是否需要用户登录
        if (!this.ls.autoAccessToken()) {
            console.warn('token failure, please login!');
        }

        // 获取权限
        this.getRole();
        this.systemService.getTableHeaderFilterOptions();
        // 不获取权限
        /* this.menuList = [
			{
				id: this.tools.isGuid(8),
				title: 'Layout.Navbar.Data_Visualization',
				icon: 'iconfont icon-dashboard- color-fff',
				exponded: false,
				active: false,
				children: [
					{
						title: 'Layout.Navbar.Overall',
						route: '/ccm/data-visualization/overall'
					},
					{
						title: 'Layout.Navbar.Incident_Analytics',
						route: '/ccm/data-visualization/incident-analytics'
					},
					{
						title: 'Layout.Navbar.Traffic_Analytics',
						route: '/ccm/data-visualization/traffic-analytics'
					},
					{
						title: 'Layout.Navbar.Equipment_Analytics',
						route: '/ccm/data-visualization/equipment-analytics'
					}
				]
			},
			// {
			// 	title: 'GIS',
			// 	icon: 'iconfont icon-ditu color-fff',
			// 	route: '/gis'
			// },
			{
				id: this.tools.isGuid(8),
				title: 'Layout.Navbar.Dissemination_Management',
				icon: 'iconfont icon-diqiu color-fff',
				exponded: false,
				active: false,
				children: [
					{
						title: 'Layout.Navbar.Message_Library',
						route: '/ccm/dissemination-management/message-library'
					},
					{
						title: 'Layout.Navbar.Message_Category',
						route: '/ccm/dissemination-management/message-category'
					},
					{
						title: 'Layout.Navbar.Graphic',
						route: '/ccm/dissemination-management/graphic'
					},
					{
						title: 'Layout.Navbar.Message_Template',
						route: '/ccm/dissemination-management/message-template'
					}
				]
			},
			{
				id: this.tools.isGuid(8),
				title: 'Layout.Navbar.Traffic_Management',
				icon: 'iconfont icon--jiaotongbiaozhipai color-fff',
				exponded: false,
				active: false,
				children: [
					{
						title: 'Layout.Navbar.Traffic_Alert',
						route: '/ccm/traffic-management/traffic-alert-page'
					},
					{
						title: 'Layout.Navbar.Incident_Record',
						route: '/ccm/traffic-management/incident-record'
					},
					{
						title: 'Layout.Navbar.Incident_Logs',
						route: '/ccm/traffic-management/incident-logs'
					}
				]
			},
			{
				id: this.tools.isGuid(8),
				title: 'Layout.Navbar.Equipment_Management',
				icon: 'iconfont icon-app_icons-- color-fff',
				exponded: false,
				active: false,
				children: [
					{
						title: 'Layout.Navbar.Equipment_List',
						route: '/ccm/equipment-management/equipment-list'
					},
					{
						title: 'Layout.Navbar.Equipment_Alarm',
						route: '/ccm/equipment-management/equipment-alarm'
					}
				]
			},
			{
				title: 'Layout.Navbar.Security_Management',
				icon: 'iconfont icon-anquan- color-fff',
				route: '/ccm/security-management'
			},
			{
				title: 'Layout.Navbar.Data_Management',
				icon: 'iconfont icon-riqi color-fff',
				route: '/ccm/data-management'
			},
			{
				id: this.tools.isGuid(8),
				title: 'Layout.Navbar.User_Management',
				icon: 'iconfont icon-user color-fff',
				exponded: false,
				active: false,
				children: [
					{
						title: 'Layout.Navbar.Manage_Users',
						route: '/ccm/user-management/manage-users'
					},
					{
						title: 'Layout.Navbar.Manage_Role',
						route: '/ccm/user-management/manage-role'
					},
					{
						title: 'Layout.Navbar.Manage_Access_Rights',
						route: '/ccm/user-management/manage-access-rights'
					},
					{
						title: 'Layout.Navbar.Manage_Organization',
						route: '/ccm/user-management/manage-organization'
					}
				]
			},
			{
				title: 'Layout.Navbar.Log_Management',
				icon: 'iconfont icon-icon-- color-fff',
				route: '/ccm/log-management'
			}
		]; */
    }

    // 根据roleId去拿权限,控制Menulist结构
    getRole() {
        const roleId = localStorage.getItem('role_id');
        this.auth.getAccessRightByRoleId(roleId).subscribe(
            res => {
                localStorage.setItem('menu', JSON.stringify(res.data));
                if (res['code'] === '000000') {
                    this.getMenuList(res['data']);
                } else {
                    this.msg.error(res['msg']);
                    this.ls.logOut();
                }
            },
            err => {
                this.msg.error('get role failed, please login again');
                this.ls.logOut();
            }
        );
    }

    // 获取sidebar菜单
    getMenuList(roles: MenuItem[]) {
        const parentIds = this.getParentIds(roles);
        roles = roles.filter(role => role.rightName !== 'GIS' && role.accesstype !== 'button').map(role => {
            role.show = true;
            role.title = `Layout.Navbar.${role.rightName}`;
            if (role.url) {
                role.route = role.url;
            }
            if (parentIds.includes(role.accessId)) {
                role.id = role.accessId + '';
                role.active = false;
                role.exponded = true;
            }

            if (role.icon) {
                role.icon = `iconfont ${role.icon} color-fff`;
            }

            if (
                role.rightName === 'Security_Management' ||
                role.rightName === 'Incident_Logs' ||
                role.rightName === 'Manage_Access_Rights'
            ) {
                role.show = false;
            }
            return role;
        });
        this.menuList = this.tools.createTreeData(roles, 'accessId', 'parentId');
        this.menuList.forEach((menu, idx) => {
            if (menu.rightName === 'zone Assignment') {
                menu.show = false;
            }
            if (menu.rightName === 'Traffic_Management') {
                menu.children.forEach((child, index) => {
                    if (child.rightName === 'Historical_Alert') {
                        menu.show = false;
                    }
                });
            }
        });
    }

    // 得到权限树中为父节点的节点id
    getParentIds(roles: MenuItem[]): number[] {
        const parentIds: number[] = [...new Set(roles.reduce((p, c) => [...p, c.parentId], []))];
        const accessIds: number[] = [...roles.reduce((p, c) => [...p, c.accessId], [])];
        return accessIds.filter(item => parentIds.includes(item));
    }

    // 控制 有children的节点的展开状态
    expandMenu(current: number, nzMenuCom?: NzSubMenuComponent, isChild?: boolean) {
        // 2. 点击菜单不会跳路由,非手风琴模式
        this.menuList.forEach((menu, i) => {
            if (+i === current) {
                // 如果是当前点击的节点
                // if (menu.exponded !== undefined) {
                if (!isChild) {
                    // 非子项,只控制菜单收缩
                    menu.exponded = !menu.exponded;
                } else {
                    // 收缩状态下记录点击过的子项的父级id
                    /*if (this.isCollapsed) {
                    this._currentId = menu.id;
                }*/
                }
                // 保存点击过的submenu的component ref
                /*const key = menu.id + '';
            if (!this._submenuRefMap.has(key)) {
                this._submenuRefMap.set(key, nzMenuCom);
            }*/
            }
        });
    }

    switchTrigger() {
        this.isCollapsed = !this.isCollapsed;
        // this._refreshMenuStatus();
    }

    // 同步菜单收缩恢复后的状态
    /*private _refreshMenuStatus() {
        if (this._currentId) {
            // 有currentId才做这个事情

            if (this._submenuRefMap.size > 0) {
                setTimeout(() => {
                    for (const [key, submenu] of this._submenuRefMap) {
                        const element = submenu['elementRef']['nativeElement'];
                        if (this._currentId === element.id) {
                            submenu.nzSubmenuService.setOpenState(true);
                        }

                        // 1. 点击子菜单就跳路由版本,手风琴模式
                        /!* else {
                            submenu.nzSubmenuService.setOpenState(false);
                        } *!/
                    }

                    // 设置完成后, 需要重置这个id值,等待下次菜单收缩
                    this._currentId = '';
                });
            }
        }
    }*/

    // 跳路由时设置菜单激活及展开状态
    private _setActiveRouter(url?: string) {
        for (const menu of this.menuList) {
            if (menu.exponded !== undefined && menu.children && menu.children.length > 0) {
                // 先关闭所有激活状态,在随后的判断中选择性激活
                menu.active = false;
                for (const [k, item] of menu.children.entries()) {
                    if (item.route === (url || this.router.url)) {
                        menu.exponded = true;
                        menu.active = true;
                        break;
                    }
                }
            }
        }
    }

    // 发送CCM窗口状态的消息
    private _ccmWinOpt(isOpen: boolean) {
        const data: Bully = { type: SYSTEM_EVENT.CCM_WIN_CHANGE, data: isOpen };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, data);
    }

    // 监听系统事件
    private _watchSystemEvent() {
        // 监听CCM channel事件
        const subscriptionCCM = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.CCM_CHANNEL).subscribe(res => {
            if (res['type'] === SYSTEM_EVENT.CCM_WIN_CHANGE && res['data'] === true) {
                window.location.href = 'about:blank';
            }
        });

        // 监听地图发出的业务事件
        const subscriptionMAP = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.MAP_CHANNEL).subscribe(res => {
            if (res) {
                if (res['type'] === SYSTEM_EVENT.CCM_NAVIGATE) {
                    // 之后可能会用data.pageKey来判断有无权限
                    this.router.navigate([res['data']['path']]);

                    // 用BS发送创建的事件
                    const _event: Bully = {
                        type: SYSTEM_EVENT.CREATE_EVENT,
                        data: res['data']['data'],
                        fromGis: true
                    };

                    // 延迟发送BS, 避免resetBS带来的副作用
                    setTimeout(() => {
                        this.bully.setBSubject(_event);
                    }, 1000);
                }
            }
        });
        this.subscriptions.push(subscriptionCCM, subscriptionMAP);
    }

    ngOnInit() {
        // 发布ccm窗口打开状态
        this._ccmWinOpt(true);

        // 监听系统事件
        this._watchSystemEvent();
    }
    ngAfterViewInit() {
        window.onunload = () => {
            // 关闭ccm窗口
            this._ccmWinOpt(false);
        };

        // 监听路由跳转,同步菜单状态
        this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe(e => {
            this._setActiveRouter(e['urlAfterRedirects']);
        });

        // 刷新后同步菜单状态
        setTimeout(() => this._setActiveRouter(), 2000);
    }

    ngOnDestroy(): void {
        if (this.subscriptions.length > 0) {
            for (const subscription of this.subscriptions) {
                if (subscription) {
                    subscription.unsubscribe();
                }
            }
        }

        // 离开ccm时(不是刷新或关闭窗口), 关闭频道, 销毁载体
        this.bully.closeBroadcast(MESSAGE_CHANNEL.CCM_CHANNEL);
        this.bully.closeBroadcast(MESSAGE_CHANNEL.MAP_CHANNEL);
    }
}
